package com.shaoshaohuo.app.ui.shipper;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.RunlineAdapter;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.Lineinfo;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.entity.post.CarInfo;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.utils.CityinfoUtil;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.entity.Area;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenu;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuCreator;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuItem;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cao on 2016/1/11.
 */
public class ReleaseCarActivity extends BaseActivity implements View.OnClickListener {

    private TopbarView mTopbarView;
    private ImageView iv_ad;
    private SwipeMenuListView mAddressListview;
    private View mSaveLayout;
    private Button mSaveButton;

    private TextView mStartCityText;
    private TextView mEndCityText;

    private EditText textview_weight;
    private EditText textview_tiji;

    private View layout_type;
    private TextView textview_type;


    private RunlineAdapter<Lineinfo> mAdapter;
    private List<Lineinfo> lineinfo;

    private String lastStartCityCode;
    private String lastEndCityCode;
    private CascadingMenuPopWindow cascadingMenuPopWindow;
    private CascadingMenuPopWindow cascadingMenuPopWindowStart;


    private static final int REQUEST_CODE_START = 100;
    private static final int REQUEST_CODE_END = 101;
    private Cityinfo mStartCity; //开始的市
    private Cityinfo mEndCity; //结束的市

    private AlertDialog carTypeDialog;

    private String id = "";
    private String carcid = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_car);
        initView();
        setUpView();
        requestData();
    }



    private void initView() {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
        iv_ad = (ImageView) findViewById(R.id.iv_add);
        mSaveLayout = this.findViewById(R.id.layout_save);
        mSaveButton = (Button) this.findViewById(R.id.button_save);

        mStartCityText = (TextView) this.findViewById(R.id.textview_start_city);
        mEndCityText = (TextView) this.findViewById(R.id.textview_end_city);
        mAddressListview = (SwipeMenuListView) this.findViewById(R.id.listview_address_list);

        textview_weight = (EditText) findViewById(R.id.textview_weight);
        textview_tiji = (EditText) findViewById(R.id.textview_tiji);


        layout_type = findViewById(R.id.layout_type);
        textview_type = (TextView) findViewById(R.id.textview_type);

    }


    private void setUpView() {
        mTopbarView.setCenterText("发布车源");
        mTopbarView.setLeftView(true, true);
        mTopbarView.setRightText("发布");
        mTopbarView.setRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });

        iv_ad.setOnClickListener(this);
        mSaveButton.setOnClickListener(this);
        mStartCityText.setOnClickListener(this);
        mEndCityText.setOnClickListener(this);
        layout_type.setOnClickListener(this);

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                deleteItem.setBackground(new ColorDrawable(Color.parseColor("#FF6368")));
                deleteItem.setWidth(StringHelper.dip2px(ReleaseCarActivity.this, 50));
                deleteItem.setIcon(R.drawable.icon_delete);
                menu.addMenuItem(deleteItem);
            }
        };
        mAddressListview.setMenuCreator(creator);

        mAddressListview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                showDialog("确定删除此条路线吗？", position);
                return false;
            }
        });

        mSaveLayout.setVisibility(View.GONE);
    }


    private void requestData() {
        startLoadingDialog();
        RequestService.getInstance().getUserInfo(this, UserInfoEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    lineinfo = entity.getData().getLineinfo();
                    id = entity.getData().getCarinfo().getId();
                    carcid = entity.getData().getCarinfo().getCarcid();
                    setAdapter();
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }


    protected void saveRunline(String fromcityid, String tocityid) {
        if(fromcityid.equals(lastStartCityCode) && tocityid.equals(lastEndCityCode)){
            showToast("该条常跑线路已设置，无须重复设置。");
            return;
        }
        lastStartCityCode = fromcityid;
        lastEndCityCode = tocityid;
        Lineinfo line= new Lineinfo();
        line.setFromcityid(fromcityid);
        line.setFromcityname(mStartCity.getCity_name());
        line.setTocityid(tocityid);
        line.setTocityname(mEndCity.getCity_name());
        lineinfo.add(line);
        setAdapter();
    }


    private void commit() {
        CarInfo carInfo = new CarInfo();
        carInfo.setId(id);
        carInfo.setCarcid(carcid);
        if (lineinfo != null && lineinfo.size() > 0) {
            carInfo.setOften_route(lineinfo);
        }
        String carWeight = textview_weight.getText().toString().trim();
        carInfo.setCarweight(carWeight);
        String carcubage = textview_tiji.getText().toString().trim();
        carInfo.setCarcubage(carcubage);
        String carType = textview_type.getText().toString().trim();
        if ("回程车".equals(carType)) {
            carInfo.setTriptype("2");
        }else {
            carInfo.setTriptype("1");
        }

        RequestService.getInstance().updateCar(this, carInfo, BaseEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    showToast("车源发布成功");
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });

    }


    protected void setAdapter() {
        if(mAdapter == null){
            mAdapter = new RunlineAdapter<>(this, lineinfo, false);
            mAddressListview.setAdapter(mAdapter);
        }else{
            mAdapter.setData(lineinfo);
        }
    }

    /*
 * 获取三级联动
 */
    private void showCityDialog(int REQUEST_CODE) {
        switch (REQUEST_CODE) {
            case REQUEST_CODE_START:
                StartDialog();
                break;
            case REQUEST_CODE_END:
                EndDialog();
                break;
        }


    }

    /**
     * 显示开始
     */
    private void StartDialog() {

        if (cascadingMenuPopWindowStart == null) {
            //向三级menu添加地区数据
            cascadingMenuPopWindowStart = new CascadingMenuPopWindow(this,false);
            cascadingMenuPopWindowStart
                    .setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {
                        @Override
                        public void getValue(Area city, String fullname) {
                            mStartCity = CityinfoUtil.convert(city);
                            if (mStartCity == null) {
                                mStartCityText.setText(fullname);
                            } else {
                                mStartCityText.setText(mStartCity.getCity_name());
                            }
                        }
                    });
            cascadingMenuPopWindowStart.showAsDropDown(mStartCityText, 5, 5);
        } else if (cascadingMenuPopWindowStart != null
                && cascadingMenuPopWindowStart.isShowing()) {
            cascadingMenuPopWindowStart.dismiss();
        } else {
            cascadingMenuPopWindowStart.showAsDropDown(mStartCityText, 5, 5);
        }
    }

    /**
     * 显示结束
     */
    private void EndDialog() {

        if (cascadingMenuPopWindow == null) {
            //向三级menu添加地区数据
            cascadingMenuPopWindow = new CascadingMenuPopWindow(this,false);
            cascadingMenuPopWindow
                    .setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {
                        @Override
                        public void getValue(Area city, String fullname) {
                            mEndCity = CityinfoUtil.convert(city);
                            if (mEndCity == null) {
                                mEndCityText.setText(fullname);
                            } else {
                                mEndCityText.setText(mEndCity.getCity_name());
                            }
                        }
                    });
            cascadingMenuPopWindow.showAsDropDown(mEndCityText, 5, 5);
        } else if (cascadingMenuPopWindow != null
                && cascadingMenuPopWindow.isShowing()) {
            cascadingMenuPopWindow.dismiss();
        } else {
            cascadingMenuPopWindow.showAsDropDown(mEndCityText, 5, 5);
        }
    }


    private void showDialog(String message, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                lineinfo.remove(position);
                mSaveLayout.setVisibility(View.GONE);
                setAdapter();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }




    private void selectCarType() {
        if (carTypeDialog != null && carTypeDialog.isShowing()) {
            return;
        }
        if (carTypeDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setItems(new String[]{"直发车", "回程车"}, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            textview_type.setText("直发车");
                            break;
                        case 1:
                            textview_type.setText("回程车");
                            break;
                    }
                }
            });
            carTypeDialog = builder.create();
            carTypeDialog.setTitle("车源类型");
        }
        carTypeDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_add:
                mSaveLayout.setVisibility(mSaveLayout.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                break;
            case R.id.button_save:
                if(mStartCity==null){
                    showToast("--");
                    return;
                }
                if(mEndCity==null){
                    showToast("---");
                    return;
                }
                saveRunline(mStartCity.getCityId(),mEndCity.getCityId());
                break;
            case R.id.textview_start_city:
                showCityDialog(REQUEST_CODE_START);
                break;
            case R.id.textview_end_city:
                showCityDialog(REQUEST_CODE_END);
                break;
            case R.id.layout_type:
                selectCarType();
                break;
        }

    }

    @Override
    protected void onDestroy() {
        if (cascadingMenuPopWindow != null) {
            cascadingMenuPopWindow.dismiss();
        }
        if (cascadingMenuPopWindowStart != null) {
            cascadingMenuPopWindowStart.dismiss();
        }
        super.onDestroy();
    }
}
